package com.pn.controller;

import com.pn.entity.CurrentUser;
import com.pn.entity.InStore;
import com.pn.entity.Purchase;
import com.pn.entity.Result;
import com.pn.page.Page;
import com.pn.service.InStoreService;
import com.pn.service.PurchaseService;
import com.pn.service.StoreService;
import com.pn.utils.TokenUtils;
import com.pn.utils.WarehouseConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/purchase")
@RestController
public class PurchaseController {

    @Autowired
    private PurchaseService purchaseService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private TokenUtils tokenUtils;
    @Autowired
    private InStoreService inStoreService;


    /*添加采购单url接口/purchase/purchase-add*/
    @RequestMapping("/purchase-add")
    public Result addBuyList(@RequestBody Purchase purchase) {
        return purchaseService.addPurchase(purchase);
    }

    /*查询仓库url接口/store-list*/
    @RequestMapping("/store-list")
    public Result queryStoryList() {
        return Result.ok(storeService.queryAllStore());
    }

    /*分页查询采购单url接口/purchase-page-list*/
    @RequestMapping("/purchase-page-list")
    public Result pageBuyList(Page page, Purchase purchase) {
        page = purchaseService.queryPurchaseByPage(page, purchase);
        return Result.ok(page);
    }

    /*删除采购单url接口/purchase-delete*/
    @RequestMapping("/purchase-delete/{buyId}")
    public Result removePurchase(@PathVariable Integer buyId) {
        return purchaseService.removePurchase(buyId);
    }

    /*修改入库单url接口/purchase-update*/
    @RequestMapping("/purchase-update")
    public Result setPurchase(@RequestBody Purchase purchase) {
        return purchaseService.setPurchase(purchase);
    }

    /*生成入库单接口*/
    @RequestMapping("/in-warehouse-record-add")
    public Result inStore(@RequestBody Purchase purchase, @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token) {

        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        int createBy = currentUser.getUserId();

        // 向入库单实体类设置值
        InStore inStore = new InStore();
        // 仓库id
        inStore.setStoreId(purchase.getStoreId());
        // 商品id
        inStore.setProductId(purchase.getProductId());
        // 实际入库数量
        inStore.setInNum(purchase.getFactBuyNum());
        // 操作人
        inStore.setCreateBy(createBy);

        return inStoreService.saveInStore(inStore, purchase.getBuyId());
    }

}
